import re
import time
# import winsound
from bs4 import BeautifulSoup

import requests
from PIL import Image


def timer():
    # 输出时间
    t = time.strftime('%H:%M:%S')
    return t


def loginQrCode():
    # 获取登录二维码
    url = 'https://qr.m.jd.com/show?appid=133&size=147'

    try:
        qrCode = requests.get(url)
        cookies = qrCode.headers.get('Set-cookie')
        return qrCode.content, cookies

    except Exception as e:
        print(e)


def monitor(cookies, token):
    # 判断二维码状态
    url = 'https://qr.m.jd.com/check?callback=jQuery1058594&appid=133&token={}'.format(token)
    headers = {
        'Referer': 'https://passport.jd.com/new/login.aspx?ReturnUrl=https%3A%2F%2Fwww.jd.com%2F%3Fcu%3Dtrue%26utm_source%3Dsogou-pinzhuan%26utm_medium%3Dcpc%26utm_campaign%3Dt_288551095_sogoupinzhuan%26utm_term%3D72c3e74a359c48598c6fabe6c1169112_0_8ac09db8ee5c42d19c8bd8e15bd92ac5',
        'Cookie': cookies}

    while True:
        try:
            r = requests.get(url, headers=headers)

            if 'ticket' in r.text:
                regex = re.compile(r'"ticket" : "(.*?)"')
                ticket = re.findall(regex, r.text)[0]
                return ticket

            elif '二维码未扫描，请扫描二维码' in r.text:
                print('[{}]'.format(timer()), '二维码未扫描，请扫描二维码')

            elif '二维码过期，请重新扫描' in r.text:
                print('[{}]'.format(timer()), '二维码过期，请重新扫描')

            elif '请手机客户端确认登录' in r.text:
                print('[{}]'.format(timer()), '请手机客户端确认登录')

            else:
                print('[{}]'.format(timer()), r.text)

            time.sleep(3)

        except Exception as e:
            print(e)


def getCookie(ticket, wlfstk):
    # 获取cookies
    url = 'https://passport.jd.com/uc/qrCodeTicketValidation?t={}'.format(ticket)
    headers = {'Referer': 'https://passport.jd.com/uc/login?ltype=logout'}
    cookies = {'Cookie': wlfstk}

    try:
        r = requests.get(url, headers=headers, cookies=cookies)
        cookies = requests.utils.dict_from_cookiejar(r.cookies)

        if cookies:
            print('[{}]'.format(timer()), '登录成功')
            return cookies

        else:
            print('[{}]'.format(timer()), '登录失败')

    except Exception as e:
        print(e)


def main():
    # 主函数
    qrCode, cookies = loginQrCode()

    with open(r'.\JD.png', 'wb') as f:
        f.write(qrCode)

    image = Image.open(r'.\JD.png')
    image = image.resize((300, 300))
    image.show()

    token = cookies.split(';')[1].split(',')[1].split('=')[1]
    QRCodeKey = cookies.split(';')[0]
    wlfstk = cookies.split(';')[1].split(',')[1]
    cookies = QRCodeKey + ';' + wlfstk
    ticket = monitor(cookies, token)
    cookies = getCookie(ticket, wlfstk)  # 获取到的cookies

    # 将要实现的功能
    test(cookies)


def test(cookies):
    # 城市代码
    citys_map = {
        "朝阳": "1_72_2799_0",
        "海淀": "1_2800_2848_0",
        "西城": "1_2801_2827_0",
        "东城": "1_2802_2821_0",
        "丰台": "1_2805_2832_0",
        "石景山": "1_2806_2831_0",
        "门头沟": "1_2807_51552_0",
        "房山": "1_2808_51528_0",
        "通州": "1_2809_51216_0",
        "大兴": "1_2810_4194_0",
        "顺义": "1_2812_51125_0",
        "怀柔": "1_2814_2847_0",
        "密云": "1_2816_2862_0",
        "昌平": "1_2901_2906_0",
        "平谷": "1_2953_2954_0",
        "延庆": "1_3065_51505_0"
    }

    print("请输入地区, 如:朝阳/海淀/西城")
    while True:
        city = input()

        if city in citys_map.keys():
            area = citys_map[city]
            break
        else:
            print("未找到, 请重新输入\n")

    # 商品信息
    fr = open("sku.txt", 'r+', encoding='utf-8')
    sku = eval(fr.read())  # 读取的str转换为字典
    fr.close()

    # 库存接口
    url = "https://item-soa.jd.com/getWareBusiness?area=" + area + "&skuId="

    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36 Edg/91.0.864.64",
    }

    num = 0
    while True:
        num += 1
        print(f'\n第{num}次检测')

        for key in sku:
            try:
                resp = requests.get(url + sku[key], headers=headers, cookies=cookies)

                if resp.text == "{'code':200,'limit':1}" or resp.text == "{code:0,msg:'limited'}":
                    print("访问频繁")
                elif resp.text.find("有货") > 0:
                    try:
                        if resp.json()["yuyueInfo"]["btnText"] == "等待预约":
                            m, s = divmod(resp.json()["yuyueInfo"]["countdown"], 60)
                            h, m = divmod(m, 60)
                            print(key + " %02d:%02d:%02d" % (h, m, s) + "秒后可预约")
                        elif resp.json()["yuyueInfo"]["btnText"] == "立即抢购":
                            print(key + " " + resp.json()["price"]["p"] + "元" + " 抢购中")
                            # winsound.Beep(440, 150)  # 赫兹, 持续时间(ms)
                        elif resp.json()["yuyueInfo"]["btnText"] == "立即预约":
                            print(key + " " + resp.json()["price"]["p"] + "元" + " 可预约")
                        else:
                            print(key + " " + resp.json()["price"]["p"] + "元" + " 等待抢购")
                    except:
                        if resp.json()["price"]["p"] != '-1.00':
                            print(key + " " + resp.json()["price"]["p"] + "元" + " 有货")
                            # winsound.Beep(440, 150)  # 赫兹, 持续时间(ms)

            except:
                print('无网络连接')
                time.sleep(300 * 0.001)

        print('waiting...')
        time.sleep(600)


if __name__ == '__main__':
    main()
